<template>
  <div class="avatar-container" :class="[sizeClass, shapeClass]" :style="containerStyle">
    <el-avatar
      :src="src"
      :size="avatarSize"
      :shape="shape"
      :icon="icon"
      :alt="alt"
      :fit="fit"
      v-bind="$attrs"
      @error="handleError"
    >
      <slot></slot>
    </el-avatar>
    
    <div v-if="badge" class="avatar-badge" :style="badgeStyle">
      {{ badge }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElAvatar } from 'element-plus'

// 定义属性
const props = defineProps({
  // 图片地址
  src: {
    type: String,
    default: ''
  },
  // 头像大小
  size: {
    type: [String, Number],
    default: 'default' // number / large / default / small
  },
  // 头像形状
  shape: {
    type: String,
    default: 'circle' // circle / square
  },
  // 图标
  icon: {
    type: Object,
    default: null
  },
  // 图片描述
  alt: {
    type: String,
    default: ''
  },
  // 确定图片如何适应容器框
  fit: {
    type: String,
    default: 'cover' // fill / contain / cover / none / scale-down
  },
  // 徽章内容
  badge: {
    type: [String, Number],
    default: ''
  },
  // 徽章背景色
  badgeColor: {
    type: String,
    default: '#f56c6c'
  },
  // 徽章文字颜色
  badgeTextColor: {
    type: String,
    default: '#fff'
  }
})

// 定义事件
const emit = defineEmits(['error'])

// 大小类名
const sizeClass = computed(() => {
  if (typeof props.size === 'string') {
    return `avatar-${props.size}`
  }
  return ''
})

// 形状类名
const shapeClass = computed(() => {
  return `avatar-${props.shape}`
})

// 头像大小
const avatarSize = computed(() => {
  if (typeof props.size === 'string') {
    return props.size
  }
  return props.size
})

// 容器样式
const containerStyle = computed(() => {
  if (typeof props.size === 'number') {
    return {
      width: `${props.size}px`,
      height: `${props.size}px`
    }
  }
  return {}
})

// 徽章样式
const badgeStyle = computed(() => {
  return {
    backgroundColor: props.badgeColor,
    color: props.badgeTextColor
  }
})

// 处理错误
const handleError = (e: Event) => {
  emit('error', e)
}
</script>

<style lang="scss" scoped>
.avatar-container {
  position: relative;
  display: inline-block;
  
  .el-avatar {
    width: 100%;
    height: 100%;
  }
}

.avatar-large {
  width: 50px;
  height: 50px;
}

.avatar-default {
  width: 40px;
  height: 40px;
}

.avatar-small {
  width: 30px;
  height: 30px;
}

.avatar-circle {
  border-radius: 50%;
}

.avatar-square {
  border-radius: 4px;
}

.avatar-badge {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
  min-width: 18px;
  height: 18px;
  padding: 0 5px;
  border-radius: 10px;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  white-space: nowrap;
  border: 2px solid #fff;
  box-sizing: content-box;
}
</style>